package com.shz.controller;

import com.shz.dto.Friend;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;


@Controller
public class FriendStatusController {
    private static final ConcurrentHashMap<String, Friend> friendMap = new ConcurrentHashMap<>();
    public static ConcurrentHashMap<String, Friend> getMap() {
        return friendMap;
    }
    @Resource
    private SimpMessagingTemplate simpMessagingTemplate;

    @MessageMapping("/checkFriendStatus")
    public void checkFriendStatus() {
        long currentTime = System.currentTimeMillis();
        List<String> removeList=new ArrayList<>();
        friendMap.forEach((friendId, friend) -> {
//            System.out.println(friend);
//            simpMessagingTemplate.convertAndSend("/queue/friendStatus", friend);
            if (currentTime - friend.getLastHeartbeatTime() > 5000) {
                removeList.add(friendId);
            }
        });
        for (String s : removeList) {
            friendMap.remove(s);
        }
        List<String> res=new ArrayList<>();
        for (String s : friendMap.keySet()) {
            res.add(s);
        }
        simpMessagingTemplate.convertAndSend("/queue/friendStatus", res);

    }

    @MessageMapping("/addFriendStatus")
    public void addFriendStatus(Friend friend) {
//        friend.setLastHeartbeatTime(System.currentTimeMillis());
        friendMap.put(friend.getId(), friend);
    }


}
